#pragma once
#include"ProTocol.hpp"
#include"Logger.hpp"
#include<string>
#include<functional>
#include<iostream>

using handler_t =std::function<Response(Request&req)>;

class Parser
{
public:
    Parser(handler_t handler):_handler(handler)
    {}
    std::string Parse(std::string &inbuffer)
    {
        LOG(Loglevel::DEBUG) << "inbuffer: \r\n" << inbuffer;
        std::string send_str;
        while(true)
        {
            std::string jsonstr;
            // 1. 解析报文
            int n = Protocol::Unpack(inbuffer, &jsonstr);
            if(n<0)
                exit(0);
            else if(n==0)
                break;// 我已经将inbuffer所有完整报文处理完毕
            else
            {
                LOG(Loglevel::DEBUG) << "jsonstr: \r\n" << jsonstr;
                Request req;
                 // 2. 反序列化
                if(!req.Deserialize(jsonstr))
                {
                    return std::string();
                }
                // 3. 根据req->response, 具体的业务
                Response rep = _handler(req);
                 // 4. 对resp在进行序列化
                std::string resp_json;
                if(!rep.Serialize(&resp_json))
                {
                    return std::string();
                }
                // 5. 打包
                send_str+=Protocol::Package(resp_json);
            }
        }
        return send_str;
    }
    ~Parser()
    {}
private:
    handler_t _handler;
};